package com.wuyan.locationdog.ui.device


import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.LatLng
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.ext.gone
import com.arcsoft.commonbase.ext.visible
import com.arcsoft.commonbase.widgets.SpaceItemDecoration
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.TimeUtils
import com.wuyan.locationdog.R
import com.wuyan.locationdog.adapter.TrackTimeListAdapter
import com.arcsoft.commonbase.bean.TrackTimeBean
import com.arcsoft.commonbase.ext.customShowLong
import com.arcsoft.commonbase.ext.isTrimEmpty
import com.arcsoft.commonbase.ext.setCalendarZero
import com.arcsoft.commonbase.ext.textStringTrim
import com.blankj.utilcode.util.ToastUtils
import com.wuyan.locationdog.databinding.TrackQueryActivityBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.util.maputil.MapLifecycle
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.view.TipPopup
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import java.util.Calendar

class TrackQueryActivity : BaseBindingActivity<TrackQueryActivityBinding>() {
    private val mViewModel: DeviceViewModel by viewModels()

//    private var startTimeSelectedDate: Date? = null
//    private var endTimeSelectedDate: Date? = null
    private var timePickerViewStartTime: TimePickerView? = null
    private var timePickerViewEndTime: TimePickerView? = null
    private val mAdapter by lazy { TrackTimeListAdapter(R.layout.item_track_time, null) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(MapLifecycle(binding!!.mapView, savedInstanceState))

    }


    override fun initData() {
        setTitleText("轨迹")

        binding?.apply {
            val list = mutableListOf<TrackTimeBean>()
            list.add(TrackTimeBean("今天", true))
            list.add(TrackTimeBean("昨天", false))
            list.add(TrackTimeBean("自定义", false))

            recyclerView.apply {
                layoutManager = GridLayoutManager(context, 3)
                addItemDecoration(SpaceItemDecoration(SizeUtils.dp2px(20f), SpaceItemDecoration.GRIDLAYOUT))
                adapter = mAdapter.apply {
                    setNewInstance(list)

                    addChildClickViewIds(R.id.time)
                    setOnItemChildClickListener { adapter, view, position ->
                        data.find { it.isSelect }?.isSelect = false
                        data[position].isSelect = true
                        notifyDataSetChanged()
                        if (position == 2) {
                            timeLayout.visible()
                        } else {
                            timeLayout.gone()
                        }

                    }
                }
            }
            btnStartTime.setOnClickListener {
                if (timePickerViewStartTime == null) {
                    timePickerViewStartTime = showTimePickerView(true, startTime)
                    timePickerViewStartTime?.show()
                } else {
                    timePickerViewStartTime?.show()
                }
            }
            btnEndTime.setOnClickListener {
                if (timePickerViewEndTime == null) {
                    timePickerViewEndTime = showTimePickerView(false, endTime)
                    timePickerViewEndTime?.show()
                } else {
                    timePickerViewEndTime?.show()
                }
            }
            btnSure.setOnClickListener {
                val index = mAdapter.data.indexOfFirst { it.isSelect }
                if (index == 2) {
                    if (startTime.isTrimEmpty() || endTime.isTrimEmpty()) {
                        customShowLong("请选择时间")
                        return@setOnClickListener
                    }
                    val time = TimeUtils.string2Millis(endTime.textStringTrim(),"yyyy-MM-dd HH:mm")-TimeUtils.string2Millis(startTime.textStringTrim(),"yyyy-MM-dd HH:mm")
//                    val time = TimeUtils.date2Millis(endTimeSelectedDate) - TimeUtils.date2Millis(startTimeSelectedDate)
                    if (time <= 0) {
                        customShowLong("开始时间大于结束时间")
                        return@setOnClickListener
                    } else if (time > 24 * 60 * 60 * 1000) {
                        customShowLong("最长不多超过24h")
                        return@setOnClickListener
                    }
                    DeviceHelp.startTime = startTime.text.toString()+":00"
                    DeviceHelp.endTime = endTime.text.toString()+":59"

                } else {
                    val calendar: Calendar = Calendar.getInstance()

                    if (index == 0) {
                        setCalendarZero(calendar)
                    } else {
                        calendar.add(Calendar.DATE, -1)
                        setCalendarZero(calendar)
                    }
                    val start = TimeUtils.date2String(calendar.time)
                    DeviceHelp.startTime = start
                    DeviceHelp.endTime = start.replace("00:00:00", "23:59:59")
                }

                val map = HashMap<String, Any>()
//                map["imei"] = DeviceHelp.selectDeviceBeanContent.imei
//                map["startTime"] = DeviceHelp.startTime
//                map["endTime"] = DeviceHelp.endTime
                mViewModel.deviceLocationRecord(map) {
                    TipPopup(
                        mActivity,
                        R.mipmap.pop_track,
                        "未查询到轨迹信息",
                        "抱歉，当前时间范围内无轨迹信息。可能设备尚未启用或设备已经离线 ！",
                        "知道了"
                    ).showPopupWindow()

                }

            }

//            MapHelp.getMarkerUi(layoutInflater, DeviceHelp.selectDeviceBeanContent){
//                mapView.map.addMarker(it)
//            }
//            val latLng = LatLng(DeviceHelp.selectDeviceBeanContent.gaoDeLat, DeviceHelp.selectDeviceBeanContent.gaoDeLng)

//            binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))


            mapView.map.setOnMarkerClickListener {


                true
            }


        }

    }


    private fun showTimePickerView(isStartTime: Boolean, textView: TextView): TimePickerView {
//        //前一个月的时间
//        val startDate: Calendar = Calendar.getInstance()
//        startDate.add(Calendar.DAY_OF_YEAR, -30)
//
//        val endDate: Calendar = Calendar.getInstance()
//        val year = endDate.get(Calendar.YEAR)
//        val month = endDate.get(Calendar.MONTH)
//        val date = endDate.get(Calendar.DATE)
//        endDate.set(year, month, date)

        return TimePickerBuilder(mActivity) { date, v ->

//            if (isStartTime) {
//                startTimeSelectedDate = date
//            } else {
//                endTimeSelectedDate = date
//            }

            textView.text = TimeUtils.date2String(date,"yyyy-MM-dd HH:mm")


        }.setType(booleanArrayOf(true, true, true, true, true, false)) // 全部显示
            .setContentTextSize(14) //滚轮文字大小
            .setOutSideCancelable(false) //点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(false) //是否循环滚动
            .isAlphaGradient(false)
            .setItemVisibleCount(5)
            .setCancelColor(Color.parseColor("#8C8C8C"))
            .setLineSpacingMultiplier(4F)
//            .setDate(endDate) // 如果不设置的话，默认是系统时间*/
//            .setRangDate(startDate, endDate) //起始终止年月日设定
            .setLabel("年", "月", "日", "时", "分", "秒") //默认设置为年月日时分秒
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .build()

    }


    override fun observe() {
        super.observe()

        mViewModel.trackBean.observe(this) {
            DeviceHelp.instantTrackBeanContent = it.content
            ActivityUtils.startActivity(TrackDetailActivity::class.java)

        }
    }

}